package com.acme.bankapp.domain.bank;

public class EmailService {
    private static final BlockingQueue emailQueue = new BlockingQueue();
    private static volatile boolean isInterrupted = false;

    static {
        new Thread() {

            @Override
            public void run() {
                try {
                    while (!(isInterrupted && emailQueue.isEmpty())) {
                        Email emailToSend = emailQueue.remove();
                        if (emailToSend == null) {
                            continue;
                        }
                        sendEmail(emailToSend);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Email Service Thread has finished");
            }
        }.start();
    }

    public static void sendNotificationEmail(Email email) {
        emailQueue.add(email);
    }

    private static void sendEmail(Email email) throws InterruptedException {
        Thread.sleep(5000);
        System.out.println(email + " has sent");
    }

    public static void close() {
        isInterrupted = true;
        emailQueue.interrupt();
    }
}
